package com.sd.repay.service.impl;

import com.sd.repay.dao.BaseDao;
import com.sd.repay.service.BindCardService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 绑卡记录接口实现
 * @date 2018年01月31日
 */
@Service
public class BindCardServiceImpl implements BindCardService {

    @Autowired
    private BaseDao baseDao;

    /**
     * 新增绑卡记录
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public int saveBindCardRecord(Map<String, String> map) throws Exception {
        String sql = " INSERT INTO t_bind_card_record(bind_no, acq_code, merchant_no, card_no, account_no, account_name, mobile_no, id_card_no, resp_code, resp_msg, create_time)" +
                " VALUES(?,?,?,?,?,?,?,?,?,?,?) ";
        List<Object> params = new ArrayList<>();
        params.add(map.get("bindNo"));
        params.add(map.get("acqCode"));
        params.add(map.get("merchantNo"));
        params.add(map.get("cardNo"));
        params.add(map.get("accountNo"));
        params.add(map.get("accountName"));
        params.add(map.get("mobileNo"));
        params.add(map.get("idCardNo"));
        params.add(map.get("respCode"));
        params.add(map.get("respMsg"));
        params.add(StringUtils.isBlank(map.get("createTime")) ? new Date() : map.get("createTime"));

        return baseDao.execute(sql, params.toArray());
    }

    /**
     * 根据绑卡订单号获取绑卡记录
     *
     * @param bindNo
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getRecordByBindNo(String bindNo) throws Exception {
        String sql = " SELECT * FROM t_bind_card_record WHERE bind_no = ? ";
        return baseDao.findFirst(sql, bindNo);
    }

    /**
     * 根据商户号，通道编号，卡号获取最近绑卡记录
     *
     * @param merchantNo
     * @param acqCode
     * @param cardNo
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getRecordByMerAndAcqAndCard(String merchantNo, String acqCode, String cardNo) throws Exception {
        String sql = " SELECT * FROM t_bind_card_record WHERE merchant_no = ? AND acq_code = ? AND card_no = ? ORDER BY create_time DESC LIMIT 1";
        return baseDao.findFirst(sql, new Object[]{merchantNo, acqCode, cardNo});
    }
}
